package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R sendMsg(HttpSession session, @RequestBody Map<String,String> map ){//map里边包含的东西
        //1.获取手机号
        String phone = map.get("phone");
        //2.随机生成验证码Va
//        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String code="1111";
        //3.调用工具类发送短信验证码
//        SMSUtils.sendMessage("提瓦大陆个人博客","SMS_460770178",phone,code);
        //4.---把验证码存入session key:phone value:code---
        //session里边已经有了  重复发起也不会在往里边添加
        session.setAttribute(phone,code);
        return R.success("发送短信验证码成功");
    }
    //用户登录
    @PostMapping("/login")
    public R login(HttpSession session,@RequestBody Map<String ,String>map){
        //1.获取用户输入手机号 验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2.获取session中的验证码
        Object codeInSession = session.getAttribute(phone);
        //3.比对用户输入的验证码和session中的验证码

        if (codeInSession==null || !codeInSession.equals(code)){
            //3.1如果不一样 抛出业务异常
            throw new CustomException("验证码错误");
        }
        //4.根据手机号判断用户是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);
        //4.1如果不存在?注册(把用户的信息存入数据库)
        if (user==null){
             user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //5.判断用户登录的状态
        if (user.getStatus()==0){
            //5.1如果已禁用 不允许 抛出业务异常
            throw new CustomException("用户已禁用");
        }
        //6.登陆成功 存入session
        session.setAttribute("user",user.getId());

        //7.移除登录中的验证码
        session.removeAttribute(phone);
        return R.success("登录成功");
    }

}